/**
 * Created by hsia on 2017/10/25.
 */
var parkOrgBuildJs = function(targetObj){
    this.sysUtils = new kendoUtils();
    this.targetObj = targetObj;
    this.init();
    return this;
};
parkOrgBuildJs.prototype={
    init:function(){
        var bindFieldArray = this.sysUtils.getBindFieldArray(this.targetObj);
        var bindFunctionArray = [
            {fName:"preStep",fs:this.preStep},
            {fName:"nextStep",fs:this.nextStep},
            {fName:"confirmBuild",fs:this.confirmBuild},
            {fName:"createRow",fs:this.createRow},
            {fName:"deleteRow",fs:this.deleteRow},
            {fName:"getAll",fs:this.getAll}];
        this.bindBaseModels = new bindBaseModel(null,bindFieldArray,bindFunctionArray,null);
        this.sysUtils.bindDoucment(this.bindBaseModels,this.targetObj,this);
        this.initTableWidget();
    },
    initTableWidget:function () {
        var that = this;
        that.targetObj.find("input[name=modelType]").click(function(e) {
            var modelType = this.value;
            that.setParamTable(modelType);
        });
        that.targetObj.find('#calflag').click(function(e) {
            that.setChargeTable(this.checked);
        });
        that.createTr(that.targetObj.find('#modelParams > tbody'),null);
        JsonpAjax(baseApiPath+"chargeStandard/chargeOptions?chargeType=1",null,"json",function(result){
            that.tempchargeList = result;
        },false);
        JsonpAjax(baseApiPath+"chargeStandard/chargeOptions?chargeType=0",null,"json",function(result){
            that.monthchargeList = result;
        },false);
        var charge_list = that.targetObj.find("#charge_list > tbody");
        $(Utils.getModelArrayByParentModelKey(BASIS.VEHICLE_TYPE.ROOT)).each(function(index){
            that.createTr2(charge_list,index,this.modelKey);
        });
        that.loadEqButton();

    },
    loadEqButton:function(){
        var that = this;
        var identVideo = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_0);
        var envirVideo = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_1);
        var control = Utils.getModelValueByModelKey(BASIS.DEVICE_CATEGORIES.DEVICE_CATEGORIES_3);
        var primaryDevs = that.targetObj.find("#primaryDev");     //通道下的添加通道二级菜单
        var slaveDevs = that.targetObj.find("#slaveDev");   //设备下的添加设备二级菜单
        JsonpAjax(baseApiPath+"facilities/devices",null,"json",function(result){
            console.info(result);
            $(result).each(function(){
                if(this.sFlag == 0){
                    var devHtml = '<span class="sp1"><input style="width:auto" value="'+this.deviceType+'" id="p'+this.deviceType+'" placeholder="'+this.deviceCategories+'" alt="'+this.deviceName+'" name="pdev" type="checkbox" required><label for="p'+this.deviceType+'">'+this.deviceName+'</label></span>';
                    //添加通道下的右键按钮 (所有设备均可添加到通道下面)
                    primaryDevs.append(devHtml);
                    //添加设备下的右键按钮   主控板和摄像机不能添加到设备下面
                    if(this.deviceCategories != identVideo && this.deviceCategories!=envirVideo
                        && this.deviceCategories!=control){
                        devHtml = '<span class="sp1"><input style="width:auto" value="'+this.deviceType+'" id="s'+this.deviceType+'" placeholder="'+this.deviceCategories+'" alt="'+this.deviceName+'" name="sdev" type="checkbox" required><label for="s'+this.deviceType+'">'+this.deviceName+'</label></span>';
                        slaveDevs.append(devHtml);
                    }
                }
            });

        });
    },
    setParamTable:function (modelType) {
        var that = this;
        //操作按钮隐藏
        if(modelType=='0'){//大套小
            that.targetObj.find('.function-btnBg').show();
            that.targetObj.find('#modelParams thead tr th:eq(1)').show();
        }else{
            that.targetObj.find('#modelParams thead tr th:eq(1)').hide();
            if(modelType=='2'){
                that.targetObj.find('.function-btnBg').hide();
            }else{
                that.targetObj.find('.function-btnBg').show();
            }
        }
        //显示隐藏列
        that.targetObj.find("#modelParams tbody tr").each(function(index){
            if(modelType=='0'){//大套小
                $(this).show();
                $(this).find('td').eq(1).required = true;
                $(this).find('td').eq(1).show();
            }else if(modelType=='1'){//多分区
                $(this).show();
                $(this).find('td').eq(1).required = true;
                $(this).find('td').eq(1).hide();
            }else if(modelType=='2'){//单分区
                if(index>0){
                    $(this).hide();
                }else{
                    $(this).find('td').eq(1).hide();
                    $(this).find('td').eq(1).required = false;
                }
            }
        });

    },
    setChargeTable:function (checked) {
        var that = this;
        this.targetObj.find("#charge_list tbody tr").each(function(){
            if(checked){
                $(this).find('td').eq(1).hide();
                $(this).find('td').eq(2).show();
                $(this).find('td').eq(3).show();
                $(this).find('td').eq(1)[0].children[0].required =false;
                $(this).find('td').eq(4)[0].children[0].required =false;
                $(this).find('td').eq(2)[0].children[0].required =true;
                $(this).find('td').eq(3)[0].children[0].required =true;
            }else if(!checked) {
                $(this).find('td').eq(1).show();
                $(this).find('td').eq(2).hide();
                $(this).find('td').eq(3).hide();
                $(this).find('td').eq(1)[0].children[0].required =true;
                $(this).find('td').eq(4)[0].children[0].required =true;
                $(this).find('td').eq(2)[0].children[0].required =false;
                $(this).find('td').eq(3)[0].children[0].required =false;
            }
        });
        if(checked){
            that.targetObj.find('#charge_list thead tr th:eq(1)').hide();
            that.targetObj.find('#charge_list thead tr th:eq(2)').show();
            that.targetObj.find('#charge_list thead tr th:eq(3)').show();
        }else if(!checked) {
            that.targetObj.find('#charge_list thead tr th:eq(1)').show();
            that.targetObj.find('#charge_list thead tr th:eq(2)').hide();
            that.targetObj.find('#charge_list thead tr th:eq(3)').hide();
        }
    },
    createTr : function(tbody,id) {
        var that = this;
        var tr = document.createElement("tr");
        var td_numb = document.createElement("td");
        var td_minPar = document.createElement("td");
        var td_wsn = document.createElement("td");
        var td_chnin = document.createElement("td");
        var td_chnout = document.createElement("td");

        var checkbox = document.createElement("input");
        checkbox.value = id;
        checkbox.tabindex = -1;
        checkbox.type = "checkbox";
        checkbox.name = "setRow";
        td_numb.appendChild(checkbox);

        var minPar = document.createElement("input");
        minPar.type = "text";
        minPar.value = "1";
        minPar.placeholder="1";
        minPar.name = "minParNum";
        minPar.required = true;
        minPar.pattern = '^([1-9]\\d{0}|[0-0]\\d{1}|1[0-0])$';
        minPar.setAttribute('data-validate','number');
        minPar.setAttribute('validationMessage','小分区数介于1到10');
        td_minPar.appendChild(minPar);

        var wsnNum = document.createElement("input");
        wsnNum.type = "text";
        wsnNum.value = "1";
        wsnNum.placeholder="1";
        wsnNum.name = "wsnNum";
        wsnNum.required = true;
        wsnNum.pattern = '^([1-9]\\d{0}|[0-0]\\d{1}|1[0-0])$';
        wsnNum.setAttribute('data-validate','number');
        wsnNum.setAttribute('validationMessage','工作站数介于1到10');
        td_wsn.appendChild(wsnNum);

        var chninNum = document.createElement("input");
        chninNum.type = "text";
        chninNum.value = "1";
        chninNum.placeholder="1";
        chninNum.name = "chninNum";
        chninNum.required = true;
        chninNum.pattern = '^([1-9]\\d{0}|[0-0]\\d{1}|1[0-0])$';
        chninNum.setAttribute('data-validate','number');
        chninNum.setAttribute('validationMessage','入口数介于1到10');
        td_chnin.appendChild(chninNum);

        var chnoutNum = document.createElement("input");
        chnoutNum.type = "text";
        chnoutNum.value = "1";
        chnoutNum.placeholder="1";
        chnoutNum.name = "chnoutNum";
        chnoutNum.required = true;
        chnoutNum.pattern = '^([1-9]\\d{0}|[0-0]\\d{1}|1[0-0])$';
        chnoutNum.setAttribute('data-validate','number');
        chnoutNum.setAttribute('validationMessage','出口数介于1到10');
        td_chnout.appendChild(chnoutNum);

        tr.appendChild(td_numb);
        tr.appendChild(td_minPar);
        tr.appendChild(td_wsn);
        tr.appendChild(td_chnin);
        tr.appendChild(td_chnout);

        tbody[0].appendChild(tr);
    },
    createTr2:function (tbody, id,modelKey) {
        var that = this;
        var tr = document.createElement("tr");
        var td_carType = document.createElement("td");
        var td_chargeNo = document.createElement("td");
        var td_holiday = document.createElement("td");
        var td_working = document.createElement("td");
        var td_openGate = document.createElement("td");
        var td_mtcharge = document.createElement("td");

        var carType = document.createElement("select");
        carType.name = "carType";
        carType.required = true;
        carType.setAttribute('data-validate','select');
        td_carType.appendChild(carType);
        var itm = Utils.getDataDictByModelKey(modelKey);
        var option = document.createElement("option");
        option.innerHTML = itm.modelName;
        option.value = itm.modelValue;
        option.setAttribute("selected", "selected")
        carType.appendChild(option);

        var chargeNo = document.createElement("select");
        chargeNo.name = "chargeNo";
        chargeNo.setAttribute('data-validate','select');
        td_chargeNo.appendChild(chargeNo);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        chargeNo.appendChild(defaultOption);
        $(that.tempchargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            chargeNo.appendChild(option);
        });

        var holiday = document.createElement("select");
        holiday.name = "holiday";
        holiday.setAttribute('data-validate','select');
        td_holiday.appendChild(holiday);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        holiday.appendChild(defaultOption);
        $(that.tempchargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            holiday.appendChild(option);
        });

        var working = document.createElement("select");
        working.name = "working";
        working.setAttribute('data-validate','select');
        td_working.appendChild(working);
        var defaultOption = document.createElement("option");
        defaultOption.innerHTML = "";
        working.appendChild(defaultOption);
        $(that.tempchargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            working.appendChild(option);
        });

        working.addEventListener('keydown', function(e) {
            if (e.keyCode == 9) {
                if ($(this).parents("tr").next().length < 1) {
                    var $_no_input = $(this).parents("tr").find("select[name=carType]");
                    var _val = $_no_input.val();
                    if (_val == "" || _val == undefined || !_val) {
                        e.returnValue = false;
                        e.cancel = true;
                        $_no_input.focus();
                        return;
                    }
                    e.returnValue = false;
                    e.cancel = true;
                    new chargeBinfo(undefined, _this.targetObj.find("#charge_list")).addToList(_this);
                    _this.targetObj.find("#charge_list tbody tr:last select[name=carType]").focus();
                    return;
                }
            }
        });
        //创建开闸方式下拉列表  A闸 B闸
        var basisGate = Utils.getModelArrayByParentModelKey(BASIS.GATE_TYPE.ROOT);
        var openGate = $("<input style='width:99%' name='openGate'  required >");
        td_openGate.appendChild(openGate[0]);

        //创建月租收费标准
        var mtCharge = document.createElement("select");
        mtCharge.name = "mtCharge";
        mtCharge.setAttribute('data-validate','select');
        td_mtcharge.appendChild(mtCharge);
        mtCharge.appendChild(defaultOption);
        $(that.monthchargeList).each(function (inx, itm) {
            var option = document.createElement("option");
            option.innerHTML = itm.name;
            option.value = itm.code;
            mtCharge.appendChild(option);
        });
        tr.appendChild(td_carType);
        tr.appendChild(td_chargeNo);
        tr.appendChild(td_holiday);
        tr.appendChild(td_working);
        tr.appendChild(td_mtcharge);
        tr.appendChild(td_openGate);
        tbody[0].appendChild(tr);
        //初始化控件
        var that = this;
        var kendoMultiSelect =  openGate.kendoMultiSelect({
            placeholder:"--请选择--",
            dataTextField:"modelName",
            dataValueField:"modelValue",
            dataSource:basisGate
        }).data("kendoMultiSelect");

    },
    deleteRow : function(e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        that.targetObj.find("input[name=\"setRow\"]:checked").each(function(inx, itm) {
            $(itm).parents("tr").remove();
        });
    },
    createRow : function(e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        var model = '';
        that.targetObj.find("input[name=modelType]").each(function () {
            if(this.checked){
                model=this.value;
            }
        });
        new chargeBinfo( that.targetObj.find("#modelParams"),null,model).addToList(that);
        that.setParamTable(model);
    },
    getAll:function (e) {
        var that = this;
        if (!isEmpty(e)) {
            that = $(e.target).data("that");
        }
        that.targetObj.find('input[name=setRow]').prop('checked', e.target.checked);
    },
    /**
     * 上一步
     * @param id
     */
    preStep:function (e) {

    },
    /**
     * 下一步
     * @param id
     */
    nextStep:function (e) {

        var name = e.target.name;
        var id = name.substr(0,1)+'_'+name.substr(1,1);
        var nextid = e.target.hash.substr(1,3);
        var that =  $(e.target).data("that");

        if(validityForm(that.targetObj.find('#'+id))){
            if(nextid=='t_2'){
                that.targetObj.find("input[name=modelType]").each(function() {
                    if(this.checked){
                        that.setParamTable(this.value);
                    }

                });
            }else if(nextid=='t_3'){
                that.setChargeTable(that.targetObj.find("#calflag")[0].checked);
            }else if(nextid=='t_4'){
                var point=true;
                that.targetObj.find("#charge_list > tbody tr").each(function (inx, itm) {
                    var cols = $(itm).find("td");
                    var openGate = $(cols[5]).find("input[name='openGate']").data("kendoMultiSelect").value();
                    if(null == openGate || openGate.length<=0){
                        notification({ title:"提示信息",message:"请选择开闸方式!！"},'info');
                        point = false;
                    }
                });
                return point;
            }
        }else{
            return false;
        }

    },
    /**
     * 确认提交
     * @param e
     */
    confirmBuild:function (e) {
        var that = this;
        if(e){
            that =  $(e.target).data("that");
        }
        if(validityForm(that.targetObj.find('#t_4'))){
            var url = baseApiPath+"autobuild/build";
            var buildInfo = that.sysUtils.getBindDocJson();
            var sendJson=buildInfo;
            for(var o in buildInfo){
                if(o.indexOf('_') !=-1){
                    var strArray = o.substring(o.indexOf('_')+1);
                    var name = o.substring(0, o.indexOf('_'));
                    var jsonA = {};
                    jsonA[name] = that.recursionObjectName(strArray,buildInfo[o]) ;
                    delete buildInfo[o];
                    sendJson =$.extend(true,buildInfo,jsonA);
                }
            }
            var model='';
            that.targetObj.find("input[name=modelType]").each(function () {
                if(this.checked){
                    model=this.value;
                }
            });
            sendJson = $.extend(true,sendJson,{modelType:model});
            var masc={masc:[]};
            that.targetObj.find("#modelParams > tbody tr").each(function (inx,itm) {
                var cols = $(itm).find("td");
                var minPar = $(cols[1]).find("input").val();
                var wsnNum = $(cols[2]).find("input").val();
                var chninNum = $(cols[3]).find("input").val();
                var chnoutNum = $(cols[4]).find("input").val();
                if(model=='0'){
                    masc.masc[inx]={minPar:minPar,wsnNum:wsnNum,chninNum:chninNum,chnoutNum:chnoutNum};
                }else{
                    masc.masc[inx]={wsnNum:wsnNum,chninNum:chninNum,chnoutNum:chnoutNum};
                }
            });
            //合并json对象
            sendJson = $.extend(true,sendJson,masc);

            var calcheck = that.targetObj.find('#calflag')[0].checked;
            var calTypeFlag=calcheck?'1':'0';
            var jsonD= {equipmentManagements:{charge:{chargelist:{},calTypeFlag:calTypeFlag}}};
            that.targetObj.find("#charge_list > tbody tr").each(function (inx, itm) {
                var cols = $(itm).find("td");
                var carType = $(cols[0]).find("select").val();
                var chargeNo = $(cols[1]).find("select").val();
                var holiday = $(cols[2]).find("select").val();
                var working = $(cols[3]).find("select").val();
                var mtCharge = $(cols[4]).find("select[name='mtCharge']").val();
                var openGate = $(cols[5]).find("input[name='openGate']").data("kendoMultiSelect").value();
                if(calcheck){
                    jsonD.equipmentManagements.charge.chargelist["charge"+inx] = JSON.stringify({carType:carType,holiday:holiday,working:working,gateType:openGate.toString(),mtCharge:mtCharge});
                }else if(!calcheck){
                    jsonD.equipmentManagements.charge.chargelist["charge"+inx] = JSON.stringify({carType:carType,chargeNo:chargeNo,gateType:openGate.toString(),mtCharge:mtCharge});
                }
            });

            //合并json对象
            sendJson = $.extend(true,sendJson,jsonD);
            var primaryDev={primaryDev:[]};
            that.targetObj.find("#primaryDev input[type=checkbox]").each(function (inx,itm) {
                if(this.checked){
                    primaryDev.primaryDev[inx] = {deviceName:this.alt,deviceType:this.value,deviceCategories:this.placeholder};
                }
            });
            sendJson = $.extend(true,sendJson,primaryDev);
            var slaveDev={slaveDev:[]};
            that.targetObj.find("#slaveDev input[type=checkbox]").each(function (inx,itm) {
                if(this.checked){
                    slaveDev.slaveDev[inx] = {deviceName:this.alt,deviceType:this.value,deviceCategories:this.placeholder};
                }
            });
            sendJson = $.extend(true,sendJson,slaveDev);
            JsonpAjax(url,JSON.stringify(sendJson),"json",function(result){
                /*setTimeout(function() {
                    orgMain.loadMain(true);
                },1000);*/

            });
        }
    },
    recursionObjectName : function (strArray,val) {
        if (strArray.indexOf('_') == -1){
            var jsonC = {};
            jsonC[strArray]=val;
            return jsonC;
        }
        var name = strArray.substring(0, strArray.indexOf('_'));
        strArray = strArray.substring(strArray.indexOf('_')+1);
        var jsonB = {};
        jsonB[name] = this.recursionObjectName(strArray,val);
        return jsonB;
    }
}

var chargeBinfo = function( table,id,modelType) {
    if (id == undefined || !id) {
        this.id = "d-" + new Date().getTime();
    } else {
        this.id = id;
    }
    this.table = table;
    this.modelType = modelType;
    return this;
}
chargeBinfo.prototype = {
    addToList : function(e) {
        e.createTr(this.table.find("tbody"),this.id,this.modelType);
    }
}